package cn.itcast.recycleviewdemo;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class GoodsAdapter extends RecyclerView.Adapter<GoodsAdapter.GoodsViewHolder> {

    private Context mContext;
    private List<GoodsBean> recommendList;

    //构造
    public GoodsAdapter(Context context, List<GoodsBean> recommendList) {
        this.mContext = context;
        this.recommendList = recommendList;
    }


    /**
     * 创建列表组件
     *解析布局
     * @param parent
     * @param viewType
     * @return
     */

    @Override
    public GoodsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_item, null);
        return new GoodsViewHolder(view);
    }

    /**
     * 绑定数据
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder( GoodsViewHolder holder, final int position) {


        holder.nameTv.setText(recommendList.get(position).getName());
        holder.imageIdTv.setImageResource(recommendList.get(position).getImageId());
        //设置子项的点击事件
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(mContext,"click view:"+position,Toast.LENGTH_SHORT).show();

                if(myClickListener!=null){
                    myClickListener.onClickTest(position);
                }

            }
        });

    }

    IMyClickListener myClickListener=null;

    public void setClick(IMyClickListener clicker){
        myClickListener =clicker;
    }

    interface IMyClickListener {
        void onClickTest(int i);
    }
    
    @Override
    public int getItemCount() {
        return recommendList.size();
    }

    public class GoodsViewHolder extends RecyclerView.ViewHolder {
        TextView nameTv;
        ImageView imageIdTv;


        public GoodsViewHolder(View view) {
            super(view);
            this.nameTv = view.findViewById(R.id.recommend_item_text);
            this.imageIdTv = view.findViewById(R.id.recommend_item_image);
        }
    }
}
